<?php

namespace app\admin\controller;

use app\admin\validate\MemberValidate;
use app\service\FinancialLogService;
use app\service\MemberService;
use app\service\PayCoinService;
use app\service\PaymentService;
use think\exception\ValidateException;
use think\facade\App;
use think\helper\Str;

class Member extends Admin
{
    public function __construct(MemberService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "会员列表");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where = [];
        if (!empty($params["status"])) {
            $where[] = ['status', '=', $params["status"]];
        }
        if (!empty($params["email"])) {
            $where[] = ['email', 'like', "%{$params['email']}%"];
        }
        if (!empty($params["id"])) {
            $where[] = ['id', '=', $params["id"]];
        }
        $ret = $this->service->getList($where);
        $this->result($ret);
    }

    protected function save($data)
    {
        $action = $this->request->action();
        try {
            validate(MemberValidate::class)->scene($action)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->save($data);
        if ($ret) {
            $this->success("操作成功");
        } else {
            $this->error("保存失败");
        }
    }

    public function add()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","添加会员");
            $this->assign("vo",null);
            return $this->fetch("form");
        }
        $params = $this->request->Post();
        $data["is_agent"] = $params["is_agent"];
        $data["contract_switch"] = $params["contract_switch"];
        $data["customer_link"] = $params["customer_link"];
        $data["email"] = $params["email"];
        $data["passwd"] = $params["passwd"];
        $data["trade_passwd"] = $params["trade_passwd"];
        $data["invite_code"] =  Str::random(6);
        $trees =[];
        if (!empty($params["invite_code"])) {
            $res = $this->service->getOne(["invite_code"=>$params["invite_code"]],"id,tree");
            if (empty($res)) {
                throw new ValidateException("邀请码不存在");
            }
            if (!empty($res->tree)) {
                $trees = explode("|",$res->tree);
            }
            array_push($trees,$res->id);
            $data["pid"] =$res->id;
            $data["tree"] = implode("|",$trees);
        }
        $this->save($data);
    }

    public function edit()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","编辑会员");
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id);
            $this->assign("vo",$vo);
            return $this->fetch("form");
        }
        $params = $this->request->Post();
        $data["is_agent"] = $params["is_agent"];
        $data["contract_switch"] = $params["contract_switch"];
        $data["customer_link"] = $params["customer_link"];
        $data["id"] = $params["id"];
        if (!empty($params["passwd"])) {
            $data["passwd"] = $params["passwd"];
        }
        if (!empty($data["trade_passwd"])) {
            $data["trade_passwd"] = $params["trade_passwd"];
        }
        $this->save($data);
    }

    public function audit()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","审核");
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id,["id","idcard","realname","register_at","email"]);
            $this->assign("vo",$vo);
            return $this->fetch("audit");
        }
        $params = $this->request->Post();
        $vo = $this->service->get($params["id"],["id","audit_status"]);
        if (empty($vo)) {
            throw new ValidateException("不存在对应会员");
        }
        if ($vo->audit_status!=\app\model\Member::MEMBER_AUDIT_STATUS_APPENDING) {
            throw new ValidateException("会员未申请认证");
        }
        $data["audit_status"] =$params["audit_status"];
        $data["id"] =$params["id"];
        $this->save($data);
    }

    public function setAgent()
    {
        $params = $this->request->Post();
        try {
            validate(MemberValidate::class)->scene("agent")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $vo = $this->service->get($params["id"],["pid"]);
        if (empty($vo)) {
            throw new ValidateException("用户不存在");
        }
        if (!empty($vo["pid"])) {
            throw new ValidateException("该会员已有上级不能设置代理");
        }
        $data["id"] = $params["id"];
        $data["is_agent"] = $params["is_agent"];
        $res = $this->service->save($data);
        if (empty($res)) {
            $this->error("设置失败");
        } else {
            $this->success("设置成功");
        }
    }

    public function setWithdrawStatus()
    {
        $params = $this->request->Post();
        try {
            validate(MemberValidate::class)->scene("withdraw_status")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $vo = $this->service->get($params["id"],["id"]);
        if (empty($vo)) {
            throw new ValidateException("用户不存在");
        }
        $data["id"] = $params["id"];
        $data["withdraw_status"] = $params["withdraw_status"];
        $this->service->save($data);
        $this->success("提现状态设置成功");
    }

    public function setStatus()
    {
        $params = $this->request->Post();
        try {
            validate(MemberValidate::class)->scene("status")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $vo = $this->service->get($params["id"],["id"]);
        if (empty($vo)) {
            throw new ValidateException("用户不存在");
        }
        $data["id"] = $params["id"];
        $data["status"] = $params["status"];
        $this->service->save($data);
        $this->success("登录状态设置成功");
    }

    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","充值");
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id,["id","email"]);
            $payCoinService = $this->app->make(PayCoinService::class);
            $payCoinList = $payCoinService->getAll(["pay_status"=>\app\model\PayCoins::PAY_COINS_STATUS_ACTIVE],"id,coin_name","sort asc");
            $this->assign("vo",$vo);
            $this->assign("pay_coin_list",$payCoinList);
            return $this->fetch("pay");
        }
        $params = $this->request->Post();
        $vo = $this->service->get($params["id"],["id","email"]);
        if (empty($vo)) {
            throw new ValidateException("找不到对应用户");
        }
        $coinId =$params["coin_id"];
        $memberId = $params["id"];
        $amount =$params["amount"];
        $payType =$params["pay_type"];
        try {
            validate(MemberValidate::class)->scene("pay")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $financialService = $this->app->make(FinancialLogService::class);
        $amount = $payType==1 ? $amount:-$amount;
        $financialService->flowLog($memberId,$amount,$coinId,0,\app\model\FinancialLog::RECHARGE,"管理员充值");
        $this->success("充值成功");
    }



    public function wallet()
    {
        $params = $this->request->get();
        if (empty($params["id"])) {
            throw new ValidateException("参数错误");
        }
        $vo = $this->service->get($params["id"],["id","realname","email"],["member_coins"=>function ($query) {
            $query->field('member_id,coin_id,account_amount,frozen_amount')
                ->with(['coin' => function($query) {
                    $query->field('id,coin_name');
                }]);
        }]);
        if (empty($vo)) {
            throw new ValidateException("找不到对应用户");
        }
        $this->assign("vo",$vo);
        return $this->fetch("wallet");
    }
}